#!/usr/bin/python3
# @Time    : 2024-03-20 下午 5:21
# @Author  : MingYangHe
# @Email   : 1780040868@qq.com
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

    def getValue(self):
        return self.val

    def getNextValue(self):
        return self.next

    def setValue(self, new_val):
        self.val = new_val

    def setNextValue(self, new_next):
        self.next = new_next


class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, val):
        if not self.head:
            self.head = ListNode(val)
        else:
            current = self.head
            while current.getNextValue():
                current = current.getNextValue()
            current.setNextValue(ListNode(val))

    def printList(self):
        current = self.head
        while current:
            print(current.getValue(), end=" -> ")
            current = current.getNextValue()
        print("None")

    def find(self, val):
        current = self.head
        while current:
            if current.getValue() == val:
                return current
            current = current.getNextValue()
        return None

    def insert(self, val, index):
        new_node = ListNode(val)
        if index == 0:
            new_node.next = self.head
            self.head = new_node
            return

        current = self.head
        for _ in range(index - 1):
            if not current.getNextValue():
                raise IndexError("Index out of range")
            current = current.getNextValue()

        new_node.next = current.getNextValue()
        current.setNextValue(new_node)

    def remove(self, val):
        current = self.head
        prev = None
        while current:
            if current.getValue() == val:
                if prev:
                    prev.setNextValue(current.getNextValue())
                else:
                    self.head = current.getNextValue()
                return
            prev = current
            current = current.getNextValue()
        raise ValueError("Value not found in list")


# main函数
def main():
    ll = LinkedList()
    # 输入
    input_values = [2, 4, 3, 5, 6, 4]
    for val in input_values:
        ll.append(val)

    # 输出
    print("Initial Linked List:")
    ll.printList()

    # 插入操作
    ll.insert(8, 2)
    print("Linked List after inserting 8 at index 2:")
    ll.printList()

    # 查找操作
    node = ll.find(4)
    print(f"Node with value 4 found: {node.getValue() if node else 'not found'}")

    # 删除操作
    ll.remove(6)
    print("Linked List after removing 6:")
    ll.printList()


# 程序入口
if __name__ == "__main__":
    main()
